package jsu.blogger.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;
/*
抽象的基类过滤器 BaseFilter，其他过滤器继承实现里面的http过滤,里面已经实现了对websocket请求的自动过滤，以及登录注册的过滤
*/
public abstract class BaseFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 检查是否是 WebSocket 请求
        if (isWebSocketRequest(request)) {
            // 如果是 WebSocket 请求，直接放行
            chain.doFilter(request, response);
            return; // 不执行后续的 HTTP 过滤器逻辑
        }

        // 处理普通 HTTP 请求
        doHttpFilter(request, response, chain);
    }

    private boolean isWebSocketRequest(ServletRequest request) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String upgradeHeader = httpRequest.getHeader("Upgrade");
        return "websocket".equalsIgnoreCase(upgradeHeader);
    }

    // 抽象方法，具体过滤器实现该方法
    protected abstract void doHttpFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化代码
    }

    @Override
    public void destroy() {
        // 清理代码
    }
}